'use strict'

//获取当前日期的前7天
export function getLastDate(date, day) {
    let myDate = new Date(date);
    myDate.setDate(myDate.getDate() + day);
    let month = (myDate.getMonth() + 1).toString().length < 2 ? '0' + (myDate.getMonth() + 1) : (myDate.getMonth() + 1);
    let dayDate = (myDate.getDate()).toString().length < 2 ? '0' + myDate.getDate() : myDate.getDate();
    return myDate.getFullYear() + "-" + month + "-" + dayDate;
}

//日期格式化
export function formatDate(date, fmt) {
    if (date == undefined) {
        return '';
    }
    let myDate = new Date(date)
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (myDate.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': myDate.getMonth() + 1,
        'd+': myDate.getDate(),
        'h+': myDate.getHours(),
        'm+': myDate.getMinutes(),
        's+': myDate.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

export function padLeftZero(str) {
    return ('00' + str).substr(str.length);
};

/**
 * 克隆一个对象 深度克隆
 * @param {boolean} deep 是否深度克隆
 */
export function clone(obj, deep) {
    if (Array.isArray(obj)) {
        if (deep) {
            //深度克隆
            var newArr = [];
            for (var i = 0; i < obj.length; i++) {
                newArr.push(clone(obj[i], true));
            }
            return newArr;
        } else {
            return obj.slice();
        }
    } else if (typeof obj === "object") {
        var newObj = {};
        for (var prop in obj) {
            if (deep) {
                //深度克隆
                newObj[prop] = clone(obj[prop], deep);
            } else {
                newObj[prop] = obj[prop];
            }
        }
        return newObj;
    } else {
        //函数，原始类型 ，直接返回
        return obj; //递归的终止条件
    }
};

export function zsDebounce(fn, time, triggerNow) {
    let t = null;

    let debounced = (...args) => {
        const _self = this;

        if (t) {
            clearTimeout(t);
        }

        if (triggerNow) {
            // 这种情况保证第一次不延迟，而且一秒内一直进来都不会触发
            let exec = !t;
            t = setTimeout(function () {
                t = null;
            }, time);

            if (exec) {
                fn.apply(_self, args);
            }
        } else {
            // 和上面的if(t){}判断配合，保证第一次延迟执行
            t = setTimeout(function () {
                fn.apply(_self, args);
            }, time);
        }
    }

    debounced.remove = function () {
        clearTimeout(t);
        t = null;
    }

    return debounced;
};

export function createguid() {
    var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
    var chars = CHARS,
        uuid = [],
        i
    // rfc4122, version 4 form
    var r
    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'
    for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
            r = 0 | (Math.random() * 16)
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
        }
    }
    var ret = uuid.join('')
    var temp = ret.split("-")
    var result = "";
    temp.forEach(e => {
        result += e;
    })
    return result.toLowerCase()
};

// 格式化消息的时间字符串
export function formatMsgTimeStr(timestamp) {
    // 7天以内：
    // •          今天：显示"时:分"，如 07:19
    // •          其他：未超过24小时的显示“xx小时前”，超过24小时的显示“x天前”
    // 7天以上：
    // •          当前年度：显示月-日，如05-07 07:19
    // •          今年以前：显示年-月-日，如2020-09-10 07:19

    const currTimestamp = new Date().getTime();	// 当前时间戳

    // 7天内
    if (currTimestamp - timestamp <= 1000 * 60 * 60 * 24 * 7) {
        if (new Date(timestamp).getDate() === new Date(currTimestamp).getDate()) {	// 等于今天
            return formatDate(timestamp, 'hh:mm');
        } else if (currTimestamp - timestamp <= 1000 * 60 * 60 * 24) {	// 小于24小时，且是昨天
            return parseInt((currTimestamp - timestamp) / (1000 * 60 * 60)) + '小时前';
        } else {
            return parseInt((currTimestamp - timestamp) / (1000 * 60 * 60 * 24)) + '天前';
        }
    }
    // 7天以上
    else {
        if (new Date(timestamp).getFullYear() === new Date(currTimestamp).getFullYear()) {	// 今年
            return formatDate(timestamp, 'MM-dd hh:mm');
        } else {
            return formatDate(timestamp, 'yyyy-MM-dd hh:mm');
        }
    }

    return formatDate(timestamp, 'yyyy-MM-dd hh:mm');
}

// 格式化消息数量显示
export function formatMsgCount(count) {
    if (count <= 999) {
        return count;
    }
    return '999+';
}

// 校验字段提示
export function validateField(value, errTip) {
    if ((Array.isArray(value) && value.length === 0) || value == null || value == '') {
        uni.showToast({
            title: errTip,
            duration: 2000,
            icon: "none",
        });
        return false;
    }

    return true;
}